# 创建一个视图函数
from flask import current_app, jsonify
from flask import request
from flask import session
from flask import g

from info import constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu
from info import redis_store
from flask import render_template

@index_blu.route("/")
@user_login_data
def index():
    # 获取用户登录信息
    user = g.user


    # 展示点击排行的新闻标题
    # 查询点击量在前n位的新闻
    try:
        news_click = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)


    # 新闻首页的分类（导航部分）的展示
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

    data = {
        "user": user.to_dict() if user else None, # 如果user存在就返回user.to_dict(),如果不存在就返回None
        "news_click" : news_click,
        "categories": categories
    }
<<<<<<< HEAD
    return render_template("news/index.html", data=data)
=======
    return render_template("index.html",  data=data)
>>>>>>> d487a945d3203647ec6decb47c923f198c6df23a

@index_blu.route("/favicon.ico")
def get_web_icon():
    #小图标
    return current_app.send_static_file("news/favicon.ico")

@index_blu.route("/news_list")
def news_list():
    """ajax请求新闻列表数据"""
    # １, 获取参数(分类的ｉｄ　　cid ,当前要第几页数据page，　每页多少条数据　per_page)
    data_dict = request.args
    cid = data_dict.get("cid", 1)
    page = data_dict.get("page", 1) # 当前第几页的数据
    per_page = data_dict.get("per_page", 5) # 每页多少条数据
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    # 2, 查询数据库　查询ｎｅｗｓ表　　条件　　排序　　　分页
    filters = []
    if cid != 1: # 就是2,3,4,5,6 需要添加查询条件,而 "最新" 不需要查询条件
        filters.append(News.category_id==cid)

    try:
        paginate = News.query.filter(*filters) .order_by(News.create_time.desc()).paginate(page,per_page)

        items = paginate.items #当前页的数据
        currentPage = paginate.page  # 当前页
        totalPage = paginate.pages  # 总页数
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")

    # 把items中的每一个python对象转换为字典
    newsList = []
    for i in items:
        newsList.append(i.to_basic_dict())

    # 3, 查询成功，返回查询的数据
    return jsonify(errno=RET.OK, errmsg="查询成功", newsList = newsList, totalPage=totalPage, currentPage=currentPage)